package com.tarena.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImagServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//在内存中生成位图
		
		BufferedImage image = new BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);
		
		//封装了画笔操作
		Graphics g =  image.getGraphics();
		Random r = new Random();
		g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
		g.fillRect(0, 0, 200, 200);		//画一个矩形,四个参数，前两个是画布的坐标，后两个是长和宽
		g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
		
		//生成干扰线条。
		for(int i=1; i<500; i++){
			g.setColor(new Color(r.nextInt(255) ,r.nextInt(255),r.nextInt(255)));
			g.drawOval(r.nextInt(500),r.nextInt(500),r.nextInt(500),r.nextInt(550));
		}
		g.setFont(new Font(null, Font.BOLD|Font.ITALIC,101));
		g.drawString(r.nextInt(500)+"", 50, 50);
		
		
		//压缩成jpeg格式
		response.setContentType("image/jpeg");
		OutputStream os = response.getOutputStream();
		
		//一边压缩，一边输出，所以要有一个输出流。想把这个文件送到哪，这个流就指到那里
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
		//输出该图片
		encoder.encode(image);
	}

}
